package com.pmonitor.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weibo4j.Oauth;
import weibo4j.Weibo;

import com.pmonitor.util.SessionUtils;
import com.pmonitor.util.Utils;

public class OAuthLoginServlet extends BaseServlet {
	/** serialVersionUID.*/
	private static final long serialVersionUID = 979508873283083214L;
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doLogin(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doLogin(req, resp);
	}

	private void doLogin(HttpServletRequest req, HttpServletResponse resp) {
		String code = req.getParameter("code");
		Oauth oauth = new Oauth();
		if(Utils.isEmptyOrNull(code)){
			String respUrl = "";
			try{
				respUrl = oauth.authorize("code");
				resp.sendRedirect(respUrl);
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
		else{
			try{
				accessToken = oauth.getAccessTokenByCode(code);
				if(accessToken!=null){
					weibo = new Weibo();
					weibo.setToken(accessToken.getAccessToken());
					SessionUtils.setAccessToken(req, accessToken);
					SessionUtils.setWeibo(req, weibo);
				}
				resp.sendRedirect("home");
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
	}
}
